/**
 * @author:linjiye
 * @date: 2024/01/13
 * @desc: 自定义钩子：错误处理中间件
 **/
import {Toast} from "@ant-design/react-native";
import {router} from "expo-router";
import useClearStorage from "@/hooks/useClearStorage";

const useErrorMiddleware = store => next => action => {
    if (action.type.endsWith('/fulfilled') && action?.payload?.openErrMessage){
        let {code,message} = action.payload
        if (code !== 0 && code !== 200){
            // Toast.info(message || '接口请求错误啦~~~')
            Toast.show({
                content: message || '接口请求错误啦~~~',
                duration: 3,
                mask: false,
            })
        }
    }
    if (action.type.endsWith('/rejected') && action?.payload?.openErrMessage) {
        // const errorResponse = action.error;
        // alert(`请求失败: ${errorResponse.message}`);
        let {code,message} = action.payload?.data
        // console.log(code, message);
        if(code === 401) {
            // 跳转到登录页
            // Toast.info(message || '接口请求错误啦~~~')
            Toast.show({
                content: message || '接口请求错误啦~~~',
                duration: 3,
                mask: false,
            })
            useClearStorage()
            router.replace('/login')
        } else {
            // Toast.info(message || '请求失败，请稍后再试~~~')
            Toast.show({
                content: message || '请求失败，请稍后再试~~~',
                duration: 3,
                mask: false,
            })
        }
    }

    return next(action)
};

export default useErrorMiddleware